package com.ciwong.epaper.modules.evaluate.ui;


import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.format.DateFormat;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.TimeoutError;
import com.ciwong.ciwongwrite.utils.CWUtils;
import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.epaper.adapter.UserDKImgGridViewAdapter;
import com.ciwong.epaper.modules.epaper.adapter.UserDKWorkWeekAdapter;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.modules.epaper.util.EpaperJumpManager;
import com.ciwong.epaper.modules.epaper.util.PeterTimeCountRefresh;
import com.ciwong.epaper.modules.evaluate.bean.DKWorkDays;
import com.ciwong.epaper.modules.evaluate.bean.DkWorkDetail;

import com.ciwong.epaper.modules.msg.util.MessageJumpManager;
import com.ciwong.epaper.util.ALiYunManager;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.IVUtils;
import com.ciwong.epaper.util.IntentFlag;

import com.ciwong.epaper.util.KHBVideo.KHBVideoPlayer;
import com.ciwong.epaper.util.KHBVideo.KHBVideoPlayerStandard;

import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.StringUtils;
import com.ciwong.mobilelib.i.BaseCallBack;

import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.ciwong.mobilelib.utils.XXPermissionTool;
import com.ciwong.mobilelib.widget.CWDialog;
import com.ciwong.mobilelib.widget.NoScrollGridView;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;

import java.util.HashMap;
import java.util.List;

import java.util.Map;


/**
 * 打卡作业详情页
 */

public class UserDKWorkActivity extends BaseActivity implements View.OnClickListener {


    private KHBVideoPlayerStandard mKHBVideoPlayerStandard;




    /*private File tempFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
            getPhotoFileName());*/


    private TextView user_dk_work_day_text;

    private String title;

    private String mWorkId;

    private ImageView user_dk_audios_img;

    private DkWorkDetail dkWorkDetail;

    private LinearLayout user_dk_audios_layout;

    private String audiosDuration;

    private TextView user_dk_audios_text;

    private TextView user_dk_rule;

    private TextView user_dk_days;

    private TextView user_dk_workName;

    private TextView user_dk_workDetails;


    private boolean isPlayVideo = false;

    private boolean isRecord = false;

    private LinearLayout user_submit_lay;


    /**
     * 展开收起
     */
    private TextView user_dk_zk_twxt;

    /**
     * 判断展开收起状态
     */
    private Boolean isZkOrSq = true;


    /**
     * 视频本地保存地址
     */
    private String localVideoPath;

    /**
     * 视频地址
     */
    private String videoUri;

    private ImageView dk_video_play;


    private NoScrollGridView user_dk_btn_grid;

    private PeterTimeCountRefresh timer;


    /**
     * 提交视频地址
     */
    private Uri submitVideoUri;

    private List<String> picList = new ArrayList<>();


    private MediaPlayer mediaPlayer;

    private LinearLayout user_dk_layout;

    private String[] cheStr = {"一", "二", "三", "四", "五", "六", "七"};
    private String[] numberStr = {"1", "2", "3", "4", "5", "6", "7"};


    /**
     * 打卡按钮适配器
     */
    private UserDKWorkWeekAdapter userDKWorkWeekAdapter;

    private GridView user_dk_grid;


    /**
     * 详情页图片适配器
     */
    private UserDKImgGridViewAdapter userDKImgGridViewAdapter;
    private TextView dk_work_text;


    @Override
    protected int setView() {
        return R.layout.activity_user_dk_work;
    }


    private ImageView user_dk_zk_img;

    private RelativeLayout user_dk_zk_lay;

    private ScrollView dk_work_scroll;

    @Override
    protected void findViews() {
        Intent intent = getIntent();
        user_dk_work_day_text = (TextView) findViewById(R.id.user_dk_work_day_text);
        user_dk_audios_img = (ImageView) findViewById(R.id.user_dk_audios_img);
        user_dk_audios_layout = (LinearLayout) findViewById(R.id.user_dk_audios_layout);
        user_dk_audios_text = (TextView) findViewById(R.id.user_dk_audios_text);
        user_dk_rule = (TextView) findViewById(R.id.user_dk_rule);
        user_dk_days = (TextView) findViewById(R.id.user_dk_days);
        user_dk_workName = (TextView) findViewById(R.id.user_dk_workName);
        user_dk_workDetails = (TextView) findViewById(R.id.user_dk_workDetails);
        user_dk_btn_grid = (NoScrollGridView) findViewById(R.id.user_dk_btn_grid);
        user_dk_grid = (GridView) findViewById(R.id.user_dk_grid);
        mKHBVideoPlayerStandard = (KHBVideoPlayerStandard) findViewById(R.id.user_dk_video);
        dk_video_play = (ImageView) findViewById(R.id.dk_video_play);
        user_dk_layout = (LinearLayout) findViewById(R.id.user_dk_layout);

        user_dk_zk_twxt = (TextView) findViewById(R.id.user_dk_zk_twxt);
        user_dk_zk_img = (ImageView) findViewById(R.id.user_dk_zk_img);

        user_dk_zk_lay = (RelativeLayout) findViewById(R.id.user_dk_zk_lay);
        dk_work_text = (TextView) findViewById(R.id.dk_work_text);
        dk_work_scroll = (ScrollView) findViewById(R.id.dk_work_scroll);

        mWorkId = intent.getStringExtra(IntentFlag.INTENT_FLAG_WORK_ID);
        dk_video_play.setOnClickListener(this);
        user_dk_zk_lay.setOnClickListener(this);

        user_dk_btn_grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                DKWorkDays dkWorkDays = dkWorkDetail.getDkworkdays().get(i);
                //setUserInfo(dkWorkDays);
                if (dkWorkDetail.getIsStart() != 0) {
                    if ((dkWorkDays.getIsDk() == 0 && dkWorkDetail.getTodayIsDkDay() == 1 && dkWorkDetail.getTodayDate().getDkDateNum() == dkWorkDays.getDkDateNum())
                            || dkWorkDays.getIsDk() == 1
                            || (dkWorkDetail.getIsStart() == 1 && dkWorkDetail.getSubmitMode() == 0 && dkWorkDetail.getTodayDate().getDkDateNum() >= dkWorkDays.getDkDateNum())) {
                        EpaperJumpManager.jumpToUserDkSubmit(UserDKWorkActivity.this, R.string.go_back, dkWorkDetail, dkWorkDays, i);
                    }
                }
            }
        });


        user_dk_grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                ArrayList<String> list = new ArrayList<>();
                list.addAll(picList);
                EpaperJumpManager.jumpToScanImage(UserDKWorkActivity.this, R.string.go_back, list, i);
            }
        });


    }


    private int durationTime;


    /**
     * 获取音频时长
     *
     * @param audios
     * @return
     */
    private String getDuration(String audios) {
        MediaPlayer mediaPlayer = new MediaPlayer();
        String audiosDuration = "";
        try {
            mediaPlayer.setDataSource(audios);
            mediaPlayer.prepare();
            durationTime = mediaPlayer.getDuration();
            if (0 != durationTime) {
                audiosDuration = formatTime(durationTime);
                //释放资源
                mediaPlayer.release();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return audiosDuration;
    }

    /**
     * 格式化音频时长
     *
     * @param timeTemp
     * @return
     */
    public static String formatTime(Object timeTemp) {
        int timeParam = 0;
        if (timeTemp instanceof Integer) {
            timeParam = (Integer) timeTemp / 1000;
        }
        if (timeTemp instanceof String) {
            timeParam = Integer.valueOf((String) timeTemp);
        }

        int second = timeParam % 60;
        int minuteTemp = timeParam / 60;
        if (minuteTemp > 0) {
            int minute = minuteTemp % 60;
            int hour = minuteTemp / 60;
            if (hour > 0) {
                return (hour > 10 ? (hour + "") : ("0" + hour)) + ":" + (minute > 10 ? (minute + "") : ("0" + minute))
                        + ":" + (second > 10 ? (second + "") : ("0" + second));
            } else {
                return (minute > 10 ? (minute + "") : ("0" + minute)) + ":"
                        + (second > 10 ? (second + "") : ("0" + second));
            }
        } else {
            return "00:" + (second > 10 ? (second + "") : ("0" + second));
        }
    }


    @Override
    protected void initEvent() {

    }

    private boolean isCheckSubmit = false;


    @Override
    protected void init() {
        setValideSource(false);

    }

    @Override
    protected void loadData() {
        showCricleProgress();
        getUserDkWorkDetails(mWorkId);

    }


    @Override
    protected void preCreate() {
        super.preCreate();
    }

    public void getUserDkWorkDetails(String workId) {
        EpaperDao.getInstance().getUserDkWorkDetails(workId, new BaseExtCallBack(UserDKWorkActivity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {
            @Override
            public void failed(int errorCode, Object data) {
                hideCricleProgress();
                super.failed(errorCode, data);
                failed(data);

            }

            @Override
            public void failed(Object data) {
                if (data instanceof TimeoutError) {
                    hideCricleProgress();
                    ToastUtil.INSTANCE.toastCenterError("加载失败，检查网络重新请求");
                }

            }

            @Override
            public void success(Object data) {

                if (null != data) {
                    dkWorkDetail = (DkWorkDetail) data;
                    setDKview();
                }
            }
        });
    }

    private void setDKview() {
        dk_work_scroll.setVisibility(View.VISIBLE);
        userDKWorkWeekAdapter = new UserDKWorkWeekAdapter(UserDKWorkActivity.this, dkWorkDetail);
        user_dk_btn_grid.setAdapter(userDKWorkWeekAdapter);

        if ("" == dkWorkDetail.getVedios() || null == dkWorkDetail.getVedios()) {
            mKHBVideoPlayerStandard.setVisibility(View.GONE);
        } else {
            videoUri = dkWorkDetail.getVedios();
            mKHBVideoPlayerStandard.setVisibility(View.VISIBLE);
            initVideoView();
        }


        if ("" == dkWorkDetail.getPictures() || null == dkWorkDetail.getPictures()) {
            user_dk_grid.setVisibility(View.GONE);
        } else {
            user_dk_grid.setVisibility(View.VISIBLE);
            picList = Arrays.asList(dkWorkDetail.getPictures().split(","));

            if ((null == videoUri || "".equals(videoUri)) && picList.size() > 2) {
                user_dk_grid.setNumColumns(3);
            } else {
                user_dk_grid.setNumColumns(2);
            }
            userDKImgGridViewAdapter = new UserDKImgGridViewAdapter(UserDKWorkActivity.this, picList, dkWorkDetail.getVedios());
            user_dk_grid.setAdapter(userDKImgGridViewAdapter);
        }


        title = dkWorkDetail.getWorkName();
        setTitleText(title);
        if (dkWorkDetail.getEffectiveDate() <= System.currentTimeMillis() && null != dkWorkDetail.getTodayDate()) {
            if (dkWorkDetail.getIsStart() == 1) {
                String dayText = "已进行" + (dkWorkDetail.getTodayDate().getDkDateNum() + 1) + "/" + dkWorkDetail.getDkdays() + "天";
                String date = (dkWorkDetail.getTodayDate().getDkDateNum() + 1) + "";
                //ForegroundColorSpan 为文字前景色
                SpannableStringBuilder stringBuilder = new SpannableStringBuilder(dayText);
                ForegroundColorSpan GreenSpan = new ForegroundColorSpan(Color.parseColor("#52cc8f"));
                stringBuilder.setSpan(GreenSpan, 3, 3 + date.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                user_dk_work_day_text.setText(stringBuilder);
            } else if (dkWorkDetail.getIsStart() == 2) {
                String dayText = "已进行" + dkWorkDetail.getDkdays() + "/" + dkWorkDetail.getDkdays() + "天";
                String date = dkWorkDetail.getDkdays() + "";
                //ForegroundColorSpan 为文字前景色
                SpannableStringBuilder stringBuilder = new SpannableStringBuilder(dayText);
                ForegroundColorSpan GreenSpan = new ForegroundColorSpan(Color.parseColor("#52cc8f"));
                stringBuilder.setSpan(GreenSpan, 3, 3 + date.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                user_dk_work_day_text.setText(stringBuilder);
            } else {
                String dayText = "已进行" + 0 + "/" + dkWorkDetail.getDkdays() + "天";
                //ForegroundColorSpan 为文字前景色
                SpannableStringBuilder stringBuilder = new SpannableStringBuilder(dayText);
                ForegroundColorSpan GreenSpan = new ForegroundColorSpan(Color.parseColor("#52cc8f"));
                stringBuilder.setSpan(GreenSpan, 3, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                user_dk_work_day_text.setText(stringBuilder);
            }

        } else {
            int dkDays = dkWorkDetail.getDkdays();
            String dayText = "已进行" + dkDays + "/" + dkDays + "天";
            SpannableStringBuilder dayTextBuilder = new SpannableStringBuilder(dayText);
            ForegroundColorSpan GreenSpan = new ForegroundColorSpan(Color.parseColor("#52cc8f"));
            if (dkDays >= 10) {
                dayTextBuilder.setSpan(GreenSpan, 3, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            } else if (dkDays < 10) {
                dayTextBuilder.setSpan(GreenSpan, 3, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            } else {
                dayTextBuilder.setSpan(GreenSpan, 3, 6, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
            user_dk_work_day_text.setText(dayTextBuilder);
        }
        ///user_dk_work_day_text.setText(stringBuilder);

        if (null != dkWorkDetail.getDkRule()) {
            String dkRule = dkWorkDetail.getDkRule();
            String[] split = dkRule.split(",");
            StringBuffer sb = new StringBuffer();
            if (split.length == 7) {
                user_dk_rule.setText("打卡规则: 每天");
            } else {
                for (int i2 = 0; i2 < split.length; i2++) {
                    String s = split[i2];
                    int indext = Arrays.binarySearch(numberStr, s);
                    if (i2 == split.length - 1) {
                        sb = sb.append(cheStr[indext]);
                    } else {
                        sb = sb.append(cheStr[indext] + ", ");
                    }

                }
                user_dk_rule.setText("打卡规则: 周 " + sb.toString());
            }
        }
        if (0 != dkWorkDetail.getSendDate() && 0 != dkWorkDetail.getEffectiveDate()) {
            long sendTime = dkWorkDetail.getSendDate();
            long endTime = dkWorkDetail.getEffectiveDate();
            user_dk_days.setText("持续时间： " + CWUtils.getWidgetWorkTimeDay(sendTime * 1000) + "-" + CWUtils.getWidgetWorkTimeDay(endTime * 1000));
        }
        if (null != dkWorkDetail.getWorkName()) {
            user_dk_workName.setText(dkWorkDetail.getWorkName());
        }
        if (null != dkWorkDetail.getWorkDetails()) {
            user_dk_workDetails.setText(dkWorkDetail.getWorkDetails());
        }

        if ("".equals(dkWorkDetail.getAudios()) || null == dkWorkDetail.getAudios()) {
            user_dk_audios_layout.setVisibility(View.GONE);
        } else {
            //获取音频时长
            final String duration = getDuration(dkWorkDetail.getAudios());
            user_dk_audios_text.setText(duration);
            user_dk_audios_layout.setVisibility(View.VISIBLE);

            user_dk_audios_img.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // AudioPlayer.getInstance().play(dkWorkDetail.getAudios(),null);
                    try {
                        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                            Log.e("MediaPlayer ", "停止播放");
                            stopPlayAnimation(user_dk_audios_img);
                            user_dk_audios_text.setText(duration);
                            timer.cancel();
                            mediaPlayer.stop();
                            mediaPlayer.release();
                            mediaPlayer = null;
                        } else {
                            startPlayAnimation(user_dk_audios_img); // 开始线程，更新进度条的刻度
                            /*handler.postDelayed(startRunnable, 500);
                            // 开始线程，停止播放
                            handler.postDelayed(stopRunnable,
                                     300);*/
                            timer = new PeterTimeCountRefresh((long) durationTime, 1000, user_dk_audios_text);
                            timer.start();
                            mediaPlayer = new MediaPlayer();
                            mediaPlayer.setDataSource(dkWorkDetail.getAudios());
                            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                            mediaPlayer.prepareAsync();
                            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

                                @Override
                                public void onPrepared(MediaPlayer mp) {
                                    Log.e("MediaPlayer ", "开始播放");
                                    mediaPlayer.start();
                                }
                            });
                            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                                @Override
                                public void onCompletion(MediaPlayer mediaPlayer) {
                                    Log.e("MediaPlayer ", "停止播放");
                                    stopPlayAnimation(user_dk_audios_img);
                                }
                            });
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            });
        }
        hideCricleProgress();
    }


    /**
     * 开始播放动画
     */
    private void startPlayAnimation(ImageView imageView) {
        imageView
                .setImageResource(R.drawable.dk_bg_annimation);

        final AnimationDrawable animationDrawable = (AnimationDrawable) imageView
                .getDrawable();
        animationDrawable.start();
    }

    /**
     * 停止播放动画
     */
    private void stopPlayAnimation(ImageView imageView) {
        Drawable drawable = imageView.getDrawable();
        if (drawable != null && drawable instanceof AnimationDrawable) {
            ((AnimationDrawable) drawable).stop();
        }
        imageView.setImageResource(R.mipmap.dk_icon_sound_3);
    }


    private File cutImgFile;
    private File VideoFile;


    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.dk_video_play) {
            mKHBVideoPlayerStandard.startVideo(KHBVideoPlayer.PLAY_MODE_UNMUTE);
        } else if (id == R.id.user_dk_zk_lay) {
            if (isZkOrSq) {
                isZkOrSq = false;
                user_dk_workDetails.setVisibility(View.GONE);
                user_dk_zk_twxt.setText("展开");
                user_dk_zk_img.setImageDrawable(this.getResources().getDrawable(R.drawable.user_dk_zk));
            } else {
                isZkOrSq = true;
                user_dk_workDetails.setVisibility(View.VISIBLE);
                user_dk_zk_twxt.setText("收起");
                user_dk_zk_img.setImageDrawable(this.getResources().getDrawable(R.drawable.user_dk_sq));
            }
        }
    }




    /*protected IEvaluateEngine iEvaluateEngine;
    public String uuid = UUID.randomUUID().toString();
    *//**
     * 获取录音的地址
     *
     * @param sentence
     * @return
     *//*
    private File getSoundPath(Sentence sentence, int index)
    {
        return new File(ESystem.getAnswersUserIdMediaPathSentence(uuid),
                uuid + StringUtils.md5(sentence.getText())
                        + EConstants.AUDIO_DEFAULT_SUFFIX);
    }*/


    /**
     * 加载视频视图
     */
    private void initVideoView() {
        IVUtils.setImageWidth200(mKHBVideoPlayerStandard.thumbImageView, null);
        showGetSDcardPermissDialog();
    }

    private final int CODE_REQUEST_WRITESD_PERMISSION = 8800;
    private CWDialog getSDcardPermissDialog;

    /**
     * 获取SDcard权限提示框
     */
    private boolean showGetSDcardPermissDialog() {
        boolean isHavePermiss = XXPermissionTool.isHasPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (isHavePermiss) {
            checkSDcardpermiss();
        } else {
            if (getSDcardPermissDialog == null) {
                getSDcardPermissDialog = new CWDialog(this);
                getSDcardPermissDialog.setTitle(R.string.get_permiss_title);
                getSDcardPermissDialog.setTitleTextColor(Color.BLACK);
                getSDcardPermissDialog.setMessage(getString(R.string.get_sdcard_permiss_content), 16, Color.BLACK, Gravity.LEFT);
                getSDcardPermissDialog.setPositiveButton(R.string.get_permiss_ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getSDcardPermissDialog.dismiss();
                        checkSDcardpermiss();
                    }
                });
                getSDcardPermissDialog.setNegativeButton(R.string.get_permiss_no, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getSDcardPermissDialog.dismiss();
                    }
                });
            }
            getSDcardPermissDialog.show();
        }
        return true;
    }

    /**
     * 使用sd卡，判断权限
     */
    private boolean checkSDcardpermiss() {
        if (Build.VERSION.SDK_INT >= 23
                && getApplicationInfo().targetSdkVersion >= 23) {
            List<String> permissionList = new ArrayList<String>();
            Map<String, String> noteMap = new HashMap<>();
            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            noteMap.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, "读写本地存储权限");
            XXPermissionTool.checkPermissions(this, //
                    permissionList, //
                    noteMap, //
                    CODE_REQUEST_WRITESD_PERMISSION, //
                    new XXPermissionTool.OnCheckPermissionsFinishedListener() {
                        @Override
                        public void onCheckPermissionsFinished(int flag) {
                            if (0 == flag) {
                                initDataView();
                            }
                        }
                    });
        } else {
            initDataView();
        }
        return true;
    }

    /**
     * 设置视频播放资源
     */
    private void initDataView() {
        localVideoPath = ESystem.getDubingVideoPath() + File.separator + StringUtils.md5(videoUri.toString());
        File targetFile = new File(localVideoPath);
        if (targetFile.exists()) {
            mKHBVideoPlayerStandard.setplsyModeUrlUp(localVideoPath, KHBVideoPlayer.SCREEN_LAYOUT_LIST, KHBVideoPlayer.PLAY_MODE_UNMUTE, "");
        } else {
            mKHBVideoPlayerStandard.setplsyModeUrlUp(videoUri.toString(), KHBVideoPlayer.SCREEN_LAYOUT_LIST, KHBVideoPlayer.PLAY_MODE_UNMUTE, "");
            downWork(videoUri.toString(), localVideoPath);
        }
        //  mKHBVideoPlayerStandard.startVideo(KHBVideoPlayer.PLAY_MODE_UNMUTE);

    }

    private BaseDownloadTask task;

    public void downWork(String videoUrl, String localVideoPath) {
        //下载视频
        try {
            FileDownloader mFileDownloader = FileDownloader.getImpl();
            mFileDownloader.setMaxNetworkThreadCount(2);
            if (null != task && task.isRunning()) {
                task.cancel();
            }
            task = mFileDownloader.create(videoUrl)
                    .setPath(localVideoPath)
                    .setAutoRetryTimes(3)
                    .setTag(videoUrl)
                    .setForceReDownload(true)
                    .setListener(fileDownloadListener);
            task.start();
        } catch (Exception e) {
            e.getStackTrace();
        }
    }

    FileDownloadListener fileDownloadListener = new FileDownloadListener() {

        @Override
        protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {

            CWLog.d("down", "down_penging");
        }


        @Override
        protected void connected(BaseDownloadTask task, String etag, boolean isContinue, int soFarBytes, int totalBytes) {

            CWLog.d("down", "down_connected");
        }

        @Override
        protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {

            CWLog.d("down", "down_connected");
        }

        @Override
        protected void completed(BaseDownloadTask task) {
        }

        @Override
        protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {

        }

        @Override
        protected void error(BaseDownloadTask task, Throwable e) {
            task.cancel();
        }

        @Override
        protected void warn(BaseDownloadTask task) {
            CWLog.d("down", "down_warn");

        }
    };

 /*   private Handler handler = new Handler(Looper.getMainLooper());

    private Runnable stopRunnable = new Runnable() {
        public void run() {
            if (mediaPlayer.isPlaying()) {
                int current = mediaPlayer.getCurrentPosition();

                mediaPlayer.pause();
                handler.removeCallbacks(startRunnable);
                stopPlayAnimation();
            }
        }
    };

    private Runnable startRunnable = new Runnable() {
        public void run() {
            if (mediaPlayer.isPlaying()) {
                int current = mediaPlayer.getCurrentPosition();
            }
            handler.postDelayed(startRunnable, 500);
        }
    };*/

    @Override
    protected void onResume() {
        super.onResume();
        this.loadData();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            Log.e("MediaPlayer ", "停止播放");
            stopPlayAnimation(user_dk_audios_img);
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
        if (timer != null) {
            timer.cancel();
        }
        KHBVideoPlayer.releaseAllVideos();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        /*handler.removeCallbacks(startRunnable);
        handler.removeCallbacks(stopRunnable);*/
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            Log.e("MediaPlayer ", "停止播放");
            stopPlayAnimation(user_dk_audios_img);
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
        if (timer != null) {
            timer.cancel();
        }
        KHBVideoPlayer.releaseAllVideos();

    }


}
